package timing.ukulele.third.controller.weixin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpDraftService;
import me.chanjar.weixin.mp.api.WxMpFreePublishService;
import me.chanjar.weixin.mp.bean.draft.*;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import timing.ukulele.common.data.ResponseData;
import timing.ukulele.data.third.data.weixin.WxArticleDTO;
import timing.ukulele.data.third.data.weixin.WxDraftDTO;
import timing.ukulele.data.third.view.weixin.WxArticleVO;
import timing.ukulele.data.third.view.weixin.WxDraftVO;
import timing.ukulele.third.config.mp.WxMpConfiguration;
import java.util.ArrayList;
import java.util.List;

/**
 * 微信草稿箱
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/weixin/wxDraft")
public class WxDraftController {

    /**
     * /wxDraft/addWxDraft
     * @param wxDraftDTO
     * @return
     */
	@Operation(summary = "新增草稿箱")
	@PostMapping("/addWxDraft")
	public ResponseData<String> addWxDraft(@RequestBody WxDraftDTO wxDraftDTO) {
		try {
			String appId = wxDraftDTO.getAppId();

            List<WxMpDraftArticles> articles = new ArrayList<>();
            for (WxArticleDTO article : wxDraftDTO.getArticleList()) {
                WxMpDraftArticles wxMpDraftArticles = new WxMpDraftArticles();
                BeanUtils.copyProperties(article, wxMpDraftArticles);
                wxMpDraftArticles.setThumbMediaId(article.getMediaId());
                articles.add(wxMpDraftArticles);
            }

            WxMpAddDraft wxMpAddDraft = new WxMpAddDraft();
			wxMpAddDraft.setArticles(articles);
			WxMpDraftService wxMpDraftService = WxMpConfiguration.getMpServiceByAppId(appId).getDraftService();
			String rs = wxMpDraftService.addDraft(wxMpAddDraft);
			return ResponseData.success(rs);
		} catch (WxErrorException e) {
            return ResponseData.error("新增微信草稿箱失败" + e.getMessage());
		}
	}

    /**
     * /wxDraft/updateWxDraft
     * @param wxDraftDTO
     * @return
     */
	@Operation(summary = "修改微信草稿箱")
    @PutMapping("/updateWxDraft")
	public ResponseData<Void> updateWxDraft(@RequestBody WxDraftDTO wxDraftDTO) {
		try {
			String appId = wxDraftDTO.getAppId();
            WxMpDraftService wxMpDraftService = WxMpConfiguration.getMpServiceByAppId(appId).getDraftService();

            WxMpUpdateDraft wxMpUpdateDraft = new WxMpUpdateDraft();
            wxMpUpdateDraft.setMediaId(wxDraftDTO.getMediaId());
            int index = 0;
            for (WxArticleDTO wxArticleDTO : wxDraftDTO.getArticleList()) {
                wxMpUpdateDraft.setIndex(index);
                WxMpDraftArticles wxMpDraftArticles = new WxMpDraftArticles();
                BeanUtils.copyProperties(wxArticleDTO, wxMpDraftArticles);
                wxMpDraftArticles.setThumbMediaId(wxArticleDTO.getMediaId());
                wxMpUpdateDraft.setArticles(wxMpDraftArticles);
                wxMpDraftService.updateDraft(wxMpUpdateDraft);
                index++;
            }
			return ResponseData.success();
        } catch (WxErrorException e) {
            return ResponseData.error("修改微信草稿箱失败" + e.getMessage());
        }
	}

    /**
     * /wxDraft/materialDel
     * @param appId
     * @return
     */
	@Operation(summary = "通过ID删除微信草稿箱")
	@DeleteMapping("/materialDel")
	public ResponseData<Boolean> deleteWxDraft(String mediaId, String appId) {
		WxMpDraftService wxMpDraftService = WxMpConfiguration.getMpServiceByAppId(appId).getDraftService();
		try {
			return ResponseData.success(wxMpDraftService.delDraft(mediaId));
		} catch (WxErrorException e) {
            return ResponseData.error("删除微信草稿箱失败" + e.getMessage());
		}
	}

    /**
     * /wxDraft/page
     * @param wxDraftDTO
     * @return
     */
	@Operation(summary = "分页查询草稿箱")
	@PostMapping("/page")
	public ResponseData<IPage> getPage(@RequestBody WxDraftDTO wxDraftDTO) {
		try {
			WxMpDraftService wxMpDraftService = WxMpConfiguration.getMpServiceByAppId(wxDraftDTO.getAppId()).getDraftService();
			int count = wxDraftDTO.getPageSize();
			int offset = wxDraftDTO.getCurrent() * count - count;
            WxMpDraftList wxMpDraftList = wxMpDraftService.listDraft(offset, count);
            Page page = new Page();
            page.setTotal(wxMpDraftList.getTotalCount());
            page.setSize(wxDraftDTO.getPageSize());

            List<WxDraftVO> resultList = new ArrayList<>();
            for (WxMpDraftItem item : wxMpDraftList.getItems()) {

                WxDraftVO wxDraftVO = new WxDraftVO();
                wxDraftVO.setMediaId(item.getMediaId());

                List<WxMpDraftArticles> newsItem = item.getContent().getNewsItem();
                List<WxArticleVO> articleVOList = new ArrayList<>();
                for (WxMpDraftArticles wxMpDraftArticles : newsItem) {
                    WxArticleVO wxArticleVO = new WxArticleVO();
                    BeanUtils.copyProperties(wxMpDraftArticles, wxArticleVO);
                    String result = wxArticleVO.getContent().replaceAll("data-src=", "src=");
                    wxArticleVO.setContent(result);
                    articleVOList.add(wxArticleVO);
                }
                wxDraftVO.setArticleList(articleVOList);
                resultList.add(wxDraftVO);
            }
            page.setRecords(resultList);
            return ResponseData.success(page);
		} catch (WxErrorException e) {
            return ResponseData.error("查询微信草稿箱失败" + e.getMessage());
		}
	}

	/**
	 * /wxDraft/publish
	 * @param wxDraftDTO
	 * @return
	 */
	@Operation(summary = "发布草稿箱")
	@PostMapping("/publishWxDraft")
	public ResponseData<Void> publishWxDraft(@RequestBody WxDraftDTO wxDraftDTO) {
		try {
			WxMpFreePublishService wxMpFreePublishService = WxMpConfiguration
                    .getMpServiceByAppId(wxDraftDTO.getAppId()).getFreePublishService();
			wxMpFreePublishService.submit(wxDraftDTO.getMediaId());
            return ResponseData.success();
		} catch (WxErrorException e) {
            return ResponseData.error("发布草稿箱失败" + e.getMessage());
		}
	}

}
